package com.leetcode.problems025;


import com.leetcode.util.ListNode;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public ListNode reverseKGroup(ListNode head, int k) {
        if(k <= 1 || head == null){
            return head;
        }

        int i = 1;
        ListNode dummyNode = new ListNode();
        dummyNode.next = head;
        ListNode preNode = dummyNode;
        ListNode startNode = head;
        ListNode endNode = head;
        while(true) {
            while (i < k && startNode != null && endNode != null) {
                endNode = endNode.next;
                i++;
            }
            if (i < k || (i == k && endNode == null)) {
                break;
            }
            ListNode[] revNodes = reverse(startNode,endNode);
            preNode.next = revNodes[0];
            preNode = revNodes[1];
            startNode = preNode.next;
            endNode = preNode.next;
            i = 1;
        }
        return dummyNode.next;
    }

    private ListNode[] reverse(ListNode startNode, ListNode endNode) {
        //保存下最后一个节点的下一个节点
        ListNode endNodeNext = endNode.next;
        ListNode curNode = startNode;
        while (curNode != null) {
            ListNode nextNode = curNode.next;
            curNode.next = endNodeNext;
            if(curNode == endNode){
                break;
            }
            endNodeNext = curNode;
            curNode = nextNode;
        }
        return new ListNode[]{endNode,startNode};
    }

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        ListNode.printListNode(new Solution().reverseKGroup(ListNode.getListFormArray(arr),6));
    }
}
